/**
 * 日志工具模块
 * @module utils/logger
 */

const winston = require('winston');

// 创建日志记录器
const logger = winston.createLogger({
  level: 'debug',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.simple()
      )
    }),
    new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
    new winston.transports.File({ filename: 'logs/combined.log' })
  ]
});

/**
 * 记录请求日志
 * @function logRequest
 * @param {Object} req - Express 请求对象
 */
logger.logRequest = (req) => {
  logger.info('收到请求', {
    method: req.method,
    url: req.originalUrl,
    body: req.body
  });
};

/**
 * 记录错误日志
 * @function logError
 * @param {Error} error - 错误对象
 */
logger.logError = (error) => {
  if (error instanceof SyntaxError && error.status === 400 && 'body' in error) {
    logger.error('JSON 解析错误:', error.message);
  } else {
    logger.error('发生错误:', {
      message: error.message,
      stack: error.stack
    });
  }
};

module.exports = logger; 